import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../service/http.service';
import { HttpRouterService } from '../../service/http-router.service';
import { StorageService } from '../../service/storage.service';
import { Router, ActivatedRoute } from '@angular/router';
import { CityData } from '../../city.data';
import _ from 'underscore';
declare var mui: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {

  public step = '';

  public _cityList = [];
  public province = '';
  public isShow = false;
  public showProvince = '全国';
  public danList = [];
  public param = '';
  public createOrderParam = '';
  public page = 1;
  public params = "";
  public showAdd = false;
  public isScreen = false;
  public maxBuy = 0;
  public citykey = "";

  public defCityList = [];
  public address = {
    province:'',
    city:''
  }

  public condition = {
    occupation: '',
    housetype: '',
    cartype: '',
    insurance: '',
    accumulationfund: '',
    socialsecurity: '',
    monthlyincome: '',
    payrolltype: '',
    workinglife: '',
    from_money: '',
    to_money: ''
  };

  constructor(
    private _http: HttpService,
    private _router: Router,
    private _activatedRoute: ActivatedRoute,
    private _storage: StorageService,
    private _httpRouter: HttpRouterService
  ) { }

  ngOnInit() {

    this._cityList =  _.map(CityData,function (item) {
      return item.children;
    })
    this._cityList = _.flatten(this._cityList,true);
    this._cityList = _.sortBy(this._cityList,function (item) {
      return item.value;
    });
    this.defCityList = _.clone(this._cityList);



    let user = this._storage.getSessionObject('user');

    this.address.city = user ? user.city : "";

    this._http.post(this._httpRouter.quanju, '').then( res => {
      if (res.code === 1) {
        this.maxBuy = parseInt(res.data.number) || 0;
        this.getDanList();
      }
    });




  }
  closeSerch(){
    this.isScreen = false;
    this.condition = {
      occupation: '',
      housetype: '',
      cartype: '',
      insurance: '',
      accumulationfund: '',
      socialsecurity: '',
      monthlyincome: '',
      payrolltype: '',
      workinglife: '',
      from_money: '',
      to_money: ''
    };
  }
  closeAddress(){
    this.isShow = false;
  }
  toserch(){
    this.isScreen = true;
  }
  serch(){
    this.isScreen = false;
    this.page = 1;
    this.getDanList();
  }

  // 城市选择框
  showChoose() {
    this.isShow = true;
  }

  // 选择城市
  checkProvince(id= '', name= '全国') {
    this.province = id;
    this.showProvince = name;
    this.isShow = false;
    this.danList = [];
  /*  if (id == '110000' || id == '120000' || id == '500000' || id == '310000'){
      this.address.province = id;
      this.address.city = "";
    }else{
      this.address.province = ""
      this.address.city = id;
    }*/
    this.address.city = id;
    this.page = 1;
    this.closeSerch();
    this.getDanList();
  }

  // 展示订单
  getDanList() {
    let token = this._storage.getSession('token');

    let param = "province="+this.address.province
      +"&city="+this.address.city
      +'&occupation=' + this.condition.occupation
      + '&housetype=' + this.condition.housetype
      + '&cartype=' + this.condition.cartype
      + '&insurance=' + this.condition.insurance
      + '&accumulationfund=' + this.condition.accumulationfund
      + '&socialsecurity=' + this.condition.socialsecurity
      + '&monthlyincome=' + this.condition.monthlyincome
      + '&payrolltype=' + this.condition.payrolltype
      + '&workinglife=' + this.condition.workinglife
      + '&from_money' + this.condition.from_money
      + '&to_money=' + this.condition.to_money
      +'&page=' + this.page
      +'&token=' + token;


    this.showAdd = false;
    this._http.post(this._httpRouter.danList, param).then(res => {
      if (res.code === 1) {
        if (res.data.length >= 20) {
          this.showAdd = true;
        }
        this.danList = _.union(this.danList, res.data);
      }
    });
  }

  danDetail(danId) {
    this._storage.setSession('danId', danId);
    this._router.navigate(['/attache/order-details'], {queryParams: {isQiang: true}});
  }

  tips(danId, danMoney, $event) {
    $event.preventDefault();
    $event.stopPropagation();
    if ( !this._storage.getSession('token')) {
      this._router.navigate(['/attache/login']);
      return;
    } else if (this._storage.getSessionObject('user').verification === 1) {
      alert('请先实名认证！');
      return;
    }


    const btnArray = ['否', '是'];
    const that = this;
    mui.confirm('您确认要抢这个单子吗？', '抢单', btnArray, function(e) {
      if (e.index === 1) {
        that.createOrderParam = 'token=' + that._storage.getSession('token') +
                                '&customer_id=' + danId +
                                '&order_money=' + danMoney;
        that._http.post(that._httpRouter.createorder, that.createOrderParam).then( res => {
          if (res.code === 1) {

            _.map(that.danList, (item) => {
              if (item.id === danId) {
                item.buy = 'yes';
              }
              return item;
            });


            alert('抢单成功');
          }
        });
      } else {
        return;
      }
    });
  }
  getCity(){
    var reg = new RegExp(this.citykey);
    let list = _.filter(this.defCityList,function (item) {
      return item.text.match(reg);
    });
    this._cityList = list

  }
  more($event) {
    $event.preventDefault();
    this.page += 1;
    this.getDanList();
  }

}
